package com.uex.dev.manage.admin.intercepter;

import com.uex.dev.manage.admin.po.UserPO;
import com.uex.dev.manage.admin.service.IUserService;
import com.uex.dev.manage.common.base.ModelResult;
import com.uex.dev.manage.common.constant.CommonConstant;
import com.uex.dev.manage.common.utils.GsonUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

/**
 * @author lzs
 * @create 2024/02/22
 * @description
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(request.getRequestURI());
        if (!(handler instanceof HandlerMethod) || HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            return true;
        }
        // 获取token
        String token = request.getHeader(CommonConstant.HEADER_TOKEN);
        // 获取登录用户
        if (token != null) {
            Optional<UserPO> loginUser = userService.getLoginUser(token);
            if (!loginUser.isPresent()) {
                String responseJson = GsonUtil.toJson(ModelResult.TOKEN_TIMEOUT_ERROR);
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println(responseJson);
                log.error("token异常", token);
                return false;
            }
            UserContext.setUserInfoLocal(loginUser.get());
        } else {
            // 如果没有token，检查是否也没有 openid
            Boolean noOpenid = (Boolean) request.getAttribute("noOpenid");
            if (Boolean.TRUE.equals(noOpenid)) {
                String responseJson = GsonUtil.toJson(ModelResult.AUTHENTICATION_REQUIRED_ERROR);
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println(responseJson);
                log.error("认证信息异常");
                return false;
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
        MDC.clear();
    }
}

